<template>
	<view>
		<u-toast ref="uToast" />
		<view class="relocation-content">
			<view class="relo-header">
				<uni-forms ref="form" :modelValue="params" :rules="rules" :label-width="50">
					<!-- <uni-forms-item label="收货单" name="deliverNo" :label-align="labelAlign" :label-width="70">
						<uni-easyinput ref="inputSelect" size="small" id="inputSelect" focus suffixIcon="search"
							trim="all" @focus="_inputFocus" v-model="params.deliverNo" maxlength="32"
							placeholder="请输入单号" confirm-type="search" @confirm="handleSearch()"
							@iconClick="handleSearch"></uni-easyinput>
					</uni-forms-item> -->
					<!-- 隐藏的扫描输入框，用于接收扫描数据 -->
					<view class="hidden-scanner">
						<uni-easyinput
							ref="scannerInput"
							v-model="scannedData"
							:focus="autoFocus"
							@confirm="processScannedData"
							class="hidden-input"
							placeholder=""
						/>
					</view>
					<!-- <view class="test-scanner">
						<uni-forms-item label="测试扫描" :label-align="labelAlign" :label-width="70">
							<uni-easyinput
								v-model="testScanData"
								@confirm="testProcessScannedData"
								placeholder="请输入测试数据: 83220L 45 20251121"
							/>
						</uni-forms-item>
					</view> -->
					<!-- 新增站台选择表单项 -->
					<uni-forms-item label="站台" name="stationNo" :label-align="labelAlign" :label-width="70" required>
						<uni-data-select 
						placeholder="请选择站台" 
						v-model="params.stationNo" 
						:localdata="stationList"
						@change="stationChange">
						</uni-data-select>
					</uni-forms-item>
					<!-- <uni-forms-item label="关键字" name="contNo" :label-align="labelAlign" :label-width="70">
						<uni-easyinput ref="contNo" v-model="spuKey" @blur="keyBlur" maxlength="6"
							placeholder="物料关键字"></uni-easyinput>
					</uni-forms-item> -->
					<!-- <uni-forms-item label="物料名称" label-align="right" :label-width="70">
						<uni-data-select :disabled="selDisable" placeholder="可选择物料名称" v-model="spuNo" :localdata="range"
							@change="selectChange"></uni-data-select>
					</uni-forms-item> -->
					<uni-forms-item label="物料编号" name="spuNo" :label-align="labelAlign" :label-width="70">
						<uni-easyinput ref="spuNo" v-model="params.spuNo" maxlength="20"
							placeholder="请输入物料编号"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="批次号" name="groupNo" :label-align="labelAlign" :label-width="70">
						<uni-easyinput ref="groupNo" v-model="params.groupNo" maxlength="20"
							placeholder="请输入批次号"></uni-easyinput>
					</uni-forms-item>
					<!-- <uni-forms-item label="容器条码" name="contNo" :label-align="labelAlign" :label-width="70">
						<uni-easyinput ref="contNo" v-model="params.contNo" maxlength="8"
							placeholder="请输入容器条码"></uni-easyinput>
					</uni-forms-item> -->
					<uni-forms-item label="实际数量" name="num" :label-align="labelAlign" :label-width="70">
						<uni-easyinput ref="num" v-model="params.num" type="number" maxlength="6"
							placeholder="请输入数量"></uni-easyinput>
					</uni-forms-item>
				
				</uni-forms>
			</view>
			<swiper class="relo-text" :current="currentIndex" :duration="500" :virtualize="true"
				@change="currentChange">
				<swiper-item v-for="(item,index) in listData" :key="index" class="form-swiper">
					<uni-row class="swiper-item">
						<uni-col :span="24">
							<text>收货单：</text>
							<view class="swiper-content">
								{{item.deliverNo}}
							</view>
						</uni-col>
					</uni-row>
					<uni-row class="swiper-item">
						<uni-col :span="24">
							<text>物料编号：</text>
							<view class="swiper-content">
								{{item.spuNo}}
							</view>
						</uni-col>
					</uni-row>
					<uni-row class="swiper-item">
						<uni-col :span="24">
							<text>物料名称：</text>
							<view class="swiper-content">
								{{item.spuName}}
							</view>
						</uni-col>
					</uni-row>
					<uni-row class="swiper-item">
						<uni-col :span="12">
							<text>计划数量：</text>
							<view class="swiper-num">
								【{{item.planQty}}】
							</view>
						</uni-col>
						<uni-col :span="12">
							<text>已收数量：</text>
							<view class="swiper-num">
								【{{item.bindQty}}】
							</view>
						</uni-col>
					</uni-row>
					<!-- <uni-row class="swiper-item">
						<uni-col :span="24">
							<text>计量单位：</text>
							<view class="swiper-des">
								{{item.unitCode}}
							</view>
						</uni-col>
					</uni-row> -->
					<uni-row class="swiper-item">
						<uni-col :span="24">
							<text>收货日期：</text>
							<view class="swiper-des">
								{{item.createDate}}
							</view>
						</uni-col>
					</uni-row>
				</swiper-item>
			</swiper>
			<uni-pagination :show-icon="true" :total="total" :pageSize="1" :current="currentIndex + 1" title="标题文字"
				@change="handleChange" />
		</view>
		<button class="next" type="primary" @click="confirm">确认收货</button>
		<button class="next" type="primary" @click="release">入库放行</button>
	</view>
</template>
</script>
<script>
	import {
		purchaseSearch,
		registerConfirm,
		contRelease
	} from '@/api/request.js'
	import {
		rules
	} from '../config/form.js'
	export default {
		name: 'rf-form',
		data() {
			return {
				selDisable: true,
				listData: [],
				// 存储数据
				clistData: [],
				range: [],
				rules: rules,
				spuNo: '',
				// 新增扫描相关数据
				scannedData: '', // 存储扫描到的原始数据
				autoFocus: true, // 控制隐藏输入框自动聚焦
				testScanData: '', // 测试用的扫描数据
				params: {
					deliverNo: '',
					lineNo: '',
					purchaseNo: '',
					contNo: '',
					spuSize: '',
					spuWeight: '1',
					planQty: '',
					num: '',
					stationNo: '', // 新增站台字段
					groupNo:'',
					limit: 1000,
					page: 1
				},
				labelAlign: 'right',
				total: 1,
				currentIndex: 0,
				weightUnit: 'kg',
				spuKey: '',
				stationList: [], // 站台列表
			};
		},
		mounted() {
			// 页面加载时获取站台列表
			this.getStationList();
			// 页面加载完成后自动聚焦到隐藏的扫描输入框
			this.$nextTick(() => {
				this.focusScanner();
			});
			},
		methods: {
			// 聚焦到扫描输入框
			focusScanner() {
			  this.autoFocus = false;
			  this.$nextTick(() => {
			    this.autoFocus = true; // 自动触发聚焦
			  });
			},
				
			// 处理扫描数据（当用户按下回车或扫描完成时触发）
			processScannedData() {
				if (!this.scannedData) return;
				
				console.log('扫描到的数据:', this.scannedData);
				this.parseAndFillData(this.scannedData);
			},
			// 测试用的扫描数据处理
			testProcessScannedData() {
				if (!this.testScanData) return;
				
				console.log('测试扫描数据:', this.testScanData);
				this.parseAndFillData(this.testScanData);
				this.testScanData = ''; // 清空测试输入框
			},
			
			// 解析和填充数据的通用方法
			parseAndFillData(data) {
				try {
					// 去除前后空格
					const cleanData = data.trim();
					
					// 按空格分割字符串
					const parts = cleanData.split(' ');
					
					if (parts.length >= 3) {
						// 格式: 83220L 45 20251121
						const materialCode = parts[0];    // 物料编号
						const quantity = parts[1];        // 数量
						const batchNo = parts[2];         // 批次号
						
						// 自动填充到表单
						this.params.spuNo = materialCode;
						this.params.num = quantity;
						this.params.groupNo = batchNo;
						
						// 显示成功提示
						uni.showToast({
							title: '数据填充成功',
							icon: 'success',
							duration: 1500
						});
						
						console.log('自动填充完成:', {
							物料编号: materialCode,
							数量: quantity,
							批次号: batchNo
						});
						
						// 清空扫描数据并重新聚焦，准备下一次扫描
						this.scannedData = '';
						this.focusScanner();
						
					} else {
						// 格式不符合预期
						uni.showModal({
							title: '数据格式错误',
							content: `数据格式应为: 物料编号 数量 批次号\n当前内容: ${cleanData}`,
							showCancel: false,
							success: () => {
								// 清空扫描数据并重新聚焦
								this.scannedData = '';
								this.focusScanner();
							}
						});
					}
				} catch (error) {
					console.error('处理数据时出错:', error);
					uni.showModal({
						title: '处理失败',
						content: '解析数据时出错，请手动输入',
						showCancel: false,
						success: () => {
							this.scannedData = '';
							this.focusScanner();
						}
					});
				}
			},
			
			stationChange(e) {
				this.params.stationNo = e;
				console.log('选择的站台:', e);
				// 选择站台后重新聚焦到扫描输入框
				this.focusScanner();
			},
			
			// 物料关键字失焦触发
			keyBlur() {
				let range = this.clistData.filter((item) => item.spuName.includes(this.spuKey))
				this.initSelect(range)
				// 输入框失焦后重新聚焦到扫描输入框
				this.focusScanner();
			},
			// 轮播下标更新
			currentChange({
				detail
			}) {
				this.currentIndex = detail.current
			},
			// 选择物料 
			selectChange(e) {
				if (!e) {
					this.listData = []
				} else {
					this.listData = this.clistData.filter((item) => item.spuNo === e)
				}
				console.log(this.clistData, this.listData);
				this.total = this.listData.length
				this.currentIndex = 0
			},
			// 输入框聚焦全选
			_inputFocus(event) {
				document.querySelector('#inputSelect input').select()
			},
			confirm() {
				console.log('开始确认收货，参数:', this.params);
				// if (this.listData.length === 0 || this.listData == null) {
				// 	uni.showModal({
				// 		title: '失败提示',
				// 		confirmColor:'#F54E40',
				// 		showCancel: false,
				// 		content: '请扫描或输入单号信息！',
				// 	})
				// 	return;
				// }
				// 表单校验
				this.$refs.form.validate().then(res => {
					// const selData = this.listData[this.currentIndex]
					const confirmParams = {
						// detailId: selData.detailId,
						// contNo: res.contNo,
						// spuNo: selData.spuNo,
						spuNo: res.spuNo,
						groupNo:res.groupNo,
						num: res.num,
						stationNo: res.stationNo,
						userId: '1004'
					}
					uni.showModal({
						title: '收货提醒',
						showCancel: true,
						// content: `是否收[${selData.spuNo}]数量[${res.num}]目标托盘[${res.contNo}]`,
						content: `是否确认收货？\n物料编号：[${res.spuNo}]\n数量：[${res.num}]\n站台：[${res.stationNo}]`,
						success: (con) => {
							if (con.confirm) {
								// 点击确认按钮请求收获接口
								registerConfirm(confirmParams, (res) => {
									if (res.code === 0) {
										uni.showModal({
											title: '成功信息',
											confirmColor:'#00ff00',
											showCancel: false,
											content: res.data,
											success: (res) => {
												if (res.confirm) {
													this.currentIndex = 0
													this.query()
													// 操作完成后重新聚焦到扫描输入框
													this.focusScanner();
												}
											}
										})
									} else {
										uni.showModal({
											title: '失败提示',
											confirmColor:'#F54E40',
											showCancel: false,
											content: res.msg,
										})
									} 
								})
							} else{
								// 用户取消后重新聚焦到扫描输入框
								this.focusScanner();
							}
						}
					})
				}).catch(error => {
					console.log('表单验证失败:', error);
					    
					uni.showModal({
					        title: '表单验证失败',
					        content: '请检查表单字段是否正确填写',
					        showCancel: false,
					        confirmColor: '#F54E40',
					        success: () => {
					          this.focusScanner();
					        }
					      });

				})
			},
			release() {
				// 表单校验
				const releaseParams = {
					// contNo: this.params.contNo,
					stationNo:this.params.stationNo,
					userId: '1004'
				}
				uni.showModal({
					title: '放行提醒',
					showCancel: true,
					// content: `已收物料是否放入容器?是否放行容器[${this.params.contNo}]`,
					content: `已收物料是否放到入库站台?是否放行站台[${this.params.stationNo}]`,
					success: (con) => {
						if (con.confirm) {
							// 点击放行按钮(放行完成无需再次查询)
							contRelease(releaseParams, (res) => {
								if (res.code === 0) {
									uni.showModal({
										title: '成功信息',
										confirmColor:'#00ff00',
										showCancel: false,
										content: res.data,
										success: (res) => {
											if (res.confirm) {
												this.currentIndex = 0
												// 操作完成后重新聚焦到扫描输入框
												this.focusScanner();
												// this.query()
											}
										}
									})
								} else {
									uni.showModal({
										title: '失败提示',
										confirmColor:'#F54E40',
										showCancel: false,
										content: res.msg,
									})
								}
							})
						} else{
							// 操作完成后重新聚焦到扫描输入框
							this.focusScanner();
						}
					}
				})
			},
			// 检验输入是否为空
			checkInput() {
				return false;
			},
			// 翻页
			handleChange(e) {
				this.currentIndex = e.current - 1
			},
			// 搜索按钮点击
			handleSearch() {
				if (!this.params.deliverNo) {
					return;
				}
				this.query()
			},
			// 搜索列表
			query(flag) {
				uni.showLoading()
				// purchaseSearch(this.params, (res) => {
				// 	console.log("res:",res);
				// 	if (res.code === 0 && res.data) {
				// 		this.listData = res.data
				// 		this.clistData = JSON.parse(JSON.stringify(res.data))
				// 		this.total = res.data.length
				// 		this.initSelect(this.clistData)
				// 	} else if (res.code != 0) {
				// 		uni.showModal({
				// 			title: '失败提示',
				// 			confirmColor:'#F54E40',
				// 			showCancel: false,
				// 			content: res.msg,
				// 		})
				// 		this.listData = {}
				// 	}
				// 	this.clearText()
				// })
			},
			// 站台选择变化
				stationChange(e) {
					this.params.stationNo = e;
					console.log('选择的站台:', e);
				},
			// 获取站台列表
				getStationList() {
					// 临时使用模拟数据
					this.stationList = [
						{ value: 'R1', text: '入库站台1' },
						{ value: 'R2', text: '入库站台2' },
						{ value: 'R3', text: '入库站台3' },
						{ value: 'R4', text: '入库站台4' },
						{ value: 'R5', text: '入库站台5' },
						{ value: 'R6', text: '入库站台6' }
					];
					console.log('使用模拟站台数据:', this.stationList);
					
					// 如果需要真实数据，取消注释下面的代码
					/*
					this.$http.get('/wms/station/page', {
						params: {
							page: 1,
							limit: 1000,
							status: 1
						}
					}).then(res => {
						if (res.code === 0 && res.data && res.data.records) {
							this.stationList = res.data.records.map(station => {
								return {
									value: station.stationNo,
									text: station.stationName || station.stationNo
								};
							});
						}
					}).catch(error => {
						console.error('获取站台列表失败:', error);
					});
					*/
				},
			// 格式化下拉框数据
			initSelect(dataList) {
				this.selDisable = false
				this.range = []
				dataList.forEach((item, index) => {
					this.range.push({
						value: item.spuNo,
						text: item.spuName,
					})
				})
			},
			clearText() {
				this.params.actlQty = ''
				this.spuNo = ''
			},
			// 扫码获取单号
			scanClick(e) {
				console.log(e)
				uni.scanCode({
					success: (res) => {
						this.params.purchaseNo = res.result
						this.params.num = 0
						this.query()
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	@import url("@/static/styles/form.scss");
</style>
<style scoped>
	::v-deep .is-disabled {
		color: black;
	}

	.relocation-content .relo-header {
		padding-bottom: 0;
	}

	.unit {
		margin-right: 5px;
	}
	
	/* 隐藏的扫描输入框样式 */
		.hidden-scanner {
			position: absolute;
			top: -1000px;
			left: -1000px;
			width: 1px;
			height: 1px;
			overflow: hidden;
			opacity: 0;
		}
		
		.hidden-input {
			width: 1px;
			height: 1px;
			border: none;
			background: transparent;
			color: transparent;
		}
		
		/* 扫描提示 */
		.scan-tip {
			font-size: 24rpx;
			color: #007AFF;
			text-align: center;
			margin: 20rpx 0;
			padding: 10rpx;
			background-color: #f0f8ff;
			border-radius: 8rpx;
		}
</style>